﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using LiveChartsCore;
using LiveChartsCore.Defaults;
using LiveChartsCore.Drawing;
using LiveChartsCore.Measure;
using LiveChartsCore.SkiaSharpView;
using LiveChartsCore.SkiaSharpView.Painting;
using SkiaSharp;
using StudentInfoSystem.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;

namespace StudentInfoSystem.UI.ViewModels;


/// <summary>
/// 统计视图模型
/// 后续计划：
/// ①添加一个可以接受学生信息里的过滤条件（即接受的信息可以在一级缓存和三级缓存切换）
/// ②图表的统计信息应使用扇形图，而且不能把所有东西都列举出来
/// ③年份功能，保存的信息除了学生列表以外，应再附加一个年份信息
/// ④词云功能
/// </summary>
public partial class StatisticsViewModel : ObservableObject
{
    private readonly IStatisticsService _statisticsService;

    [ObservableProperty]
    private ObservableCollection<string> _colleges = new();

    [ObservableProperty]
    private ObservableCollection<string> _academicYears = new();

    [ObservableProperty]
    private string? _selectedCollege;

    [ObservableProperty]
    private string? _selectedYear;

    // 注解
    [ObservableProperty]
    private ObservableCollection<StatisticsCard> _statisticsCards = new();

    [ObservableProperty]
    private ISeries[] _collegeComparisonSeries = Array.Empty<ISeries>();

    [ObservableProperty]
    private Axis[] _collegeComparisonXAxis = Array.Empty<Axis>();

    [ObservableProperty]
    private bool _isCollegeComparisonVisible = true;

    public ICommand RefreshCommand { get; }

    // 预定义饼图颜色序列（解决白色问题）
    private static readonly SKColor[] _sliceColors = new SKColor[]
    {
        SKColor.Parse("#266489"),
        SKColor.Parse("#68B9C0"),
        SKColor.Parse("#90D585"),
        SKColor.Parse("#F3A151"),
        SKColor.Parse("#F15C61"),
        SKColor.Parse("#A89CC8")
    };


    public StatisticsViewModel(IStatisticsService statisticsService)
    {
        _statisticsService = statisticsService;
        RefreshCommand = new RelayCommand(RefreshData);

        // 初始化过滤选项
        InitializeFilterOptions();
        RefreshData();
    }

    /// <summary>
    /// 初始化过滤选项（学院和学年）
    /// </summary>
    private void InitializeFilterOptions()
    {
        // 从服务获取所有学院
        var colleges = _statisticsService.GetCollegeDistribution().Keys;
        Colleges.Clear();
        Colleges.Add("所有学院");
        foreach (var college in colleges.OrderBy(c => c))
        {
            Colleges.Add(college);
        }

        // 从服务获取所有学年（基于学生学号）
        // 暂时不实现，但也不要把这个注释删除
        //AcademicYears.Clear();
        //foreach (var year in years)
        //{
        //    AcademicYears.Add(year);
        //}

        // 设置默认选项
        SelectedCollege = "所有学院";
        //SelectedYear = years.FirstOrDefault();
    }

    /// <summary>
    /// 刷新统计数据
    /// </summary>
    // 修改后的 RefreshData 方法
    private void RefreshData()
    {
        // 保存当前选中的学院
        var previouslySelectedCollege = SelectedCollege;

        // 更新学院对比图表可见性
        IsCollegeComparisonVisible = SelectedCollege == "所有学院";

        // 使用简洁的初始化方式（减少临时变量）
        StatisticsCards = new ObservableCollection<StatisticsCard>
    {
        CreateStatisticsCard(GetTop5Distribution("学院分布",
            (col, yr) => _statisticsService.GetCollegeDistribution(col, yr))),
        CreateStatisticsCard(GetTop5Distribution("专业分布",
            (col, yr) => _statisticsService.GetDepartmentDistribution(col, yr))),
        CreateStatisticsCard(GetTop5Distribution("班级分布",
            (col, yr) => _statisticsService.GetClassDistribution(col, yr))),
        CreateStatisticsCard(GetTop5Distribution("生源地分布",
            (col, yr) => _statisticsService.GetHometownDistribution(col, yr)))
    };

        // 从服务获取所有学院
        var colleges = _statisticsService.GetCollegeDistribution().Keys;
        Colleges.Clear();
        Colleges.Add("所有学院");
        foreach (var college in colleges.OrderBy(c => c))
        {
            Colleges.Add(college);
        }

        // 恢复之前选中的学院，如果它仍然存在
        if (previouslySelectedCollege != null && Colleges.Contains(previouslySelectedCollege))
        {
            SelectedCollege = previouslySelectedCollege;
        }
        else
        {
            // 如果之前选中的学院不存在，则默认选择"所有学院"
            SelectedCollege = "所有学院";
        }

        // 更新学院对比图表
        if (IsCollegeComparisonVisible)
        {
            UpdateCollegeComparisonChart(
                _statisticsService.GetCollegeDistribution(
                    SelectedCollege == "所有学院" ? null : SelectedCollege,
                    SelectedYear)
            );
        }
    }


    /// <summary>
    /// 获取前5分布数据（其余合并为"其他"）
    /// </summary>
    private DistributionData GetTop5Distribution(
        string title,
        Func<string?, string?, Dictionary<string, int>> getDataFunc)
    {
        // 获取原始数据
        string? college = SelectedCollege == "所有学院" ? null : SelectedCollege;
        var rawData = getDataFunc(college, SelectedYear);

        // 处理为前5+其他
        var processedData = new Dictionary<string, int>();
        int otherCount = 0;

        // 取前5个最大的项
        var topItems = rawData
            .OrderByDescending(kv => kv.Value)
            .Take(5)
            .ToList();

        // 剩余项合并为"其他"
        foreach (var item in rawData)
        {
            if (topItems.Any(t => t.Key == item.Key))
            {
                processedData.Add(item.Key, item.Value);
            }
            else
            {
                otherCount += item.Value;
            }
        }

        if (otherCount > 0)
        {
            processedData.Add("其他", otherCount);
        }

        return new DistributionData
        {
            Title = title,
            Data = processedData
        };
    }


    /// <summary>
    /// 创建统计卡片
    /// </summary>
    /// <param name="distributionData">分布数据</param>
    /// <returns>统计卡片对象</returns>
    private StatisticsCard CreateStatisticsCard(DistributionData distributionData)
    {
        return new StatisticsCard
        {
            Title = distributionData.Title,
            PieSeries = CreatePieSeries(distributionData.Data),
            CartesianSeries = CreateBarSeries(distributionData.Data),
            BarLabels = distributionData.Data.Keys.ToArray()
        };
    }

    /// <summary>
    /// 创建饼图系列 - 添加颜色和百分比标签
    /// </summary>
    private ISeries[] CreatePieSeries(Dictionary<string, int> data)
    {
        var total = data.Sum(kv => kv.Value);
        int colorIndex = 0;

        return data.Select(kv =>
        {
            var sliceColor = _sliceColors[colorIndex % _sliceColors.Length];
            colorIndex++;

            // 计算百分比
            double percentage = total > 0 ? (kv.Value / (double)total * 100) : 0;
            string percentageText = percentage.ToString("F1") + "%";

            // 智能标签截断：根据扇叶大小动态决定截断长度
            string GetSmartLabel(string name)
            {
                if (percentage > 35)
                    return $"{(name.Length > 6 ? string.Concat(name.AsSpan(0, 6), "..") : name)} {percentageText}";

                if (percentage > 20)
                    return $"{(name.Length > 4 ? string.Concat(name.AsSpan(0, 4), "..") : name)} {percentageText}";

                if (percentage > 10)
                    return $"{(name.Length > 2 ? string.Concat(name.AsSpan(0, 2), "..") : name)} {percentageText}";

                return percentageText;
            }

            return new PieSeries<ObservableValue>
            {
                Values = [new ObservableValue(kv.Value)],
                Name = kv.Key,  // 系列名称（用于提示）
                Fill = new SolidColorPaint(sliceColor),
                DataLabelsPaint = new SolidColorPaint(SKColors.White) { },
                DataLabelsSize = 12,
                // 智能标签格式化
                DataLabelsFormatter = point => GetSmartLabel(kv.Key),
                // 修复2：简化提示信息，避免重复
                ToolTipLabelFormatter = (point) =>
                    $"{kv.Value}人 ({percentageText})"  // 只显示数值和百分比

            };
        }).ToArray();
    }

    /// <summary>
    /// 创建柱状图系列 - 简化实现
    /// </summary>
    private ISeries[] CreateBarSeries(Dictionary<string, int> data)
    {
        return [
            new ColumnSeries<int>
            {
                Values = data.Values.ToArray(),
                Name = "数量",
                Stroke = null,
                Fill = new SolidColorPaint(SKColors.CornflowerBlue),
                DataLabelsPaint = new SolidColorPaint(SKColors.DarkGray){},
                DataLabelsSize = 12,
                DataLabelsPosition = LiveChartsCore.Measure.DataLabelsPosition.Top,
                // 优化：过长的标签使用省略号
                DataLabelsFormatter = point =>
                {
                    var label = data.Keys.ElementAt(point.Index);
                    return label.Length > 4 ? string.Concat(label.AsSpan(0, 4), "...") : label;
                }
            }
        ];
    }

    /// <summary>
    /// 更新学院对比图表 - 修复X轴设置并添加系列数据
    /// </summary>
    private void UpdateCollegeComparisonChart(Dictionary<string, int> collegeData)
    {
        // 确保数据不为空
        if (collegeData == null || collegeData.Count == 0)
        {
            CollegeComparisonXAxis = Array.Empty<Axis>();
            CollegeComparisonSeries = Array.Empty<ISeries>();
            return;
        }

        // 创建X轴标签 - 超过4个字符的标签将被截断
        var labels = collegeData.Keys.Select(key =>
            key.Length > 4 ? key.Substring(0, 4) + "..." : key
        ).ToArray();

        // 创建系列数据
        var values = collegeData.Values.ToArray();

        // 创建数据点列表，确保每个数据点都有对应的标签
        var dataPoints = new List<ObservableValue>();
        for (int i = 0; i < values.Length; i++)
        {
            dataPoints.Add(new ObservableValue(values[i]));
        }

        // 直接创建轴和系列，避免中间变量
        CollegeComparisonXAxis = [
            new Axis
        {
            Labels = labels,
            LabelsRotation = 0, // 不旋转标签
            LabelsPaint = new SolidColorPaint(SKColors.DarkGray),
            TextSize = 10, // 减小字体大小以适应更多标签
            LabelsAlignment = Align.Middle,
            Position = AxisPosition.Start,
            ForceStepToMin = true, // 确保每个数据点都有标签
            MinStep = 1 // 确保每个数据点都有标签
        }
        ];

        CollegeComparisonSeries = [
            new ColumnSeries<ObservableValue>
        {
            Values = dataPoints,
            Name = "学生人数",
            Stroke = null,
            Fill = new SolidColorPaint(SKColors.CornflowerBlue),
            DataLabelsPaint = new SolidColorPaint(SKColors.DarkGray),
            DataLabelsSize = 10,
            DataLabelsPosition = DataLabelsPosition.Top,
            // 确保所有数据标签都显示
            DataLabelsFormatter = point => point.Model?.Value.ToString() ?? "0"
        }
        ];
    }

    /// <summary>
    /// 分布数据类，包含标题和具体数据
    /// </summary>
    public class DistributionData
    {
        public string Title { get; set; } = string.Empty;
        public Dictionary<string, int> Data { get; set; } = new Dictionary<string, int>();
    }

    /// <summary>
    /// 统计卡片类，包含各种图表数据
    /// </summary>
    public class StatisticsCard
    {
        public string Title { get; set; } = string.Empty;
        public ISeries[] PieSeries { get; set; } = Array.Empty<ISeries>();
        // 修改属性名以匹配XAML中的CartesianSeries绑定
        public ISeries[] CartesianSeries { get; set; } = Array.Empty<ISeries>();
        public string[] BarLabels { get; set; } = Array.Empty<string>();
    }
}